import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import  Axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css'
import {myMixin} from './mixin/mixins'
import api from './api/api'
import fileDownload from "js-file-download";
import JsonExcel from  'vue-json-excel'
import qs from  'qs'
Vue.prototype.$qs = qs
Vue.prototype.$api = api
Vue.mixin(myMixin);
Vue.use(ElementUI)
Vue.component('downloadExcel',JsonExcel)
Vue.prototype.$axios=Axios
Vue.config.productionTip = false

Axios.interceptors.request.use(config => { 
  if (config.push === '/') { 
   } else { 
    if (localStorage.getItem('token')) { 
      //在请求头加入token，名字要和后端接收请求头的token名字一样 
      config.headers.token=localStorage.getItem('token'); 
    } 
   } 
    return config; 
  }, 
  error => { 
   return Promise.reject(error);
});

Axios.interceptors.response.use(response => { 
  //和后端token失效返回码约定
  if (response.data.code == 401) {
    ElementUI.Message({  
     message: '身份已失效', 
     type: 'warning' 
     });
    //清除token 
    localStorage.removeItem('token');
    //跳转  
    router.push({name: 'login'}); 
   } else { 
     return response 
   } 
  }, 
 error => { 
  return Promise.reject(error); 
})

router.beforeEach((to,from,next)=>{
  let token = localStorage.getItem('token')
  if(token || to.path == '/register' || to.path == '/forget'){
    next()
  }else{
    if(to.path !== '/login'){
      next({path:'/login'})
    }else{
      next()
    }
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
